package com.laiyizhan.common.service;

import com.laiyizhan.common.mapper.KvdbMapper;
import com.laiyizhan.common.model.Kvdb;
import com.laiyizhan.common.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class KvdbService {

    private static final Logger log = LoggerFactory.getLogger(KvdbService.class);

    @Autowired
    KvdbMapper kvdbMapper;

    public boolean setObject(String key, Object value) {
        if (value == null) {
            throw new IllegalArgumentException("value 不能为null");
        }
        Kvdb kvdb = new Kvdb();
        kvdb.setKey(key);
        kvdb.setValue(JsonUtil.toJson(value));
        kvdb.setCreateTime(new Date());
        return kvdbMapper.insert(kvdb) != 0;
    }

    public <T> T getObject(String key, Class<T> tClass) {
        Kvdb kvdb = kvdbMapper.selectByKey(key);
        if (kvdb != null) {
            return JsonUtil.toObject(kvdb.getValue(), tClass);
        }
        return null;
    }

    public int getCountByKey(String key) {
        return kvdbMapper.count(key);
    }

    public void removeObject(String key) {
        int result = kvdbMapper.deleteByKey(key);
        log.info("removeObject result : {}", result);
    }

    public Kvdb getKeyByValue(String value) {
        // value都是json, 所以需要转换
        return kvdbMapper.selectByValue(JsonUtil.toJson(value));
    }

    public Kvdb getValueByKey(String key) {
        return kvdbMapper.selectByKey(key);
    }
}
